package com.agileai.wm.module.daywork.handler;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.StandardListHandler;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.NullRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.DateUtil;
import com.agileai.wm.common.ExportFileHelper;
import com.agileai.wm.cxmodule.WmDayworkManage;
import com.agileai.wm.module.daywork.service.WmNoteManage;

public class WmDayworkManageListHandler
        extends StandardListHandler{
	protected String nodeIdField = "NOTE_ID";
	
    public WmDayworkManageListHandler() {
        super();
        this.editHandlerClazz = WmDayworkManageEditHandler.class;
        this.serviceId = buildServiceId(WmDayworkManage.class);
    }
    
    public ViewRenderer prepareDisplay(DataParam param){
		mergeParam(param);
		initParameters(param);
		this.setAttributes(param);
		User user = (User) this.getUser();
		param.put("USER_ID",user.getUserId());
		String query = param.getString("query");
		if("".equals(query) || query==null){
			DataRow userRecord=getService().getUserRecord(param);
			int DISPLAY_COUNT =userRecord.getInt("DISPLAY_COUNT");
			WmNoteManage wmNoteManage = this.lookupService(WmNoteManage.class);
			List<DataRow> noteRecords = wmNoteManage.findRecords(param);
			List<DataRow> displaynoteRecords = new ArrayList<DataRow>();
			List<DataRow> displayDayWorkRecords = new ArrayList<DataRow>();
			if(DISPLAY_COUNT<noteRecords.size()){
				for(int j=0;j<DISPLAY_COUNT;j++){
					DataRow dataRow=noteRecords.get(j);
					displaynoteRecords.add(dataRow);
				}
				this.setAttribute("noteRecords", displaynoteRecords);
				this.setAttribute("dayWorkRecords", displayDayWorkRecords);
			}else{
				int count =DISPLAY_COUNT-noteRecords.size();
				List<DataRow> dayWorkRecords = getService().findRecords(param);
				
				if(count >= dayWorkRecords.size()){
					for(int i=0;i<dayWorkRecords.size();i++){
						DataRow dataRow =dayWorkRecords.get(i);
						displayDayWorkRecords.add(dataRow);
					}
				}else{
					int startIndex = dayWorkRecords.size() - count;
					for(int i= startIndex; i < dayWorkRecords.size();i++){
						DataRow dataRow =dayWorkRecords.get(i);
						displayDayWorkRecords.add(dataRow);
					}
				}
				this.setAttribute("dayWorkRecords", displayDayWorkRecords);
				this.setAttribute("noteRecords", noteRecords);
			}
		}else{
			WmNoteManage wmNoteManage = this.lookupService(WmNoteManage.class);
			List<DataRow> noteRecords = wmNoteManage.findRecords(param);
			List<DataRow> dayWorkRecords = getService().findRecords(param);
			this.setAttribute("dayWorkRecords", dayWorkRecords);
			this.setAttribute("noteRecords", noteRecords);
		}
		this.setAttribute("USER_NAME", user.getUserName());
		processPageAttributes(param);
		return new LocalRenderer(getPage());
	}
    
    protected void processPageAttributes(DataParam param) {
    	setAttribute("TW_ENV",
                FormSelectFactory.create("TW_ENV_TYPE")
                                 .addSelectedValue(param.get("TW_ENV")));
    	
        initMappingItem("TW_ENV",
                        FormSelectFactory.create("TW_ENV_TYPE").getContent());
    }

    protected void initParameters(DataParam param) {
        initParamItem(param, "startDate", "");
        initParamItem(param, "endDate", "");
    }
    
    @PageAction
	public ViewRenderer saveDayWork(DataParam param) {
    	String responseText = FAIL;
    	try {
    		getService().saveDayWorkRecord(param);
    		responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
		return new AjaxRenderer(responseText);
	}
    @PageAction
   	public ViewRenderer saveDisplayCount(DataParam param) {
    	User user = (User) this.getUser();
		param.put("USER_ID",user.getUserId());
		getService().updateUserRecord(param);
		return prepareDisplay(param);
   	}
    
    @PageAction
   	public ViewRenderer deleteDayWork(DataParam param) {
   		getService().deletRecord(param);
       	return prepareDisplay(param);
   	}

    @PageAction
	public ViewRenderer saveNote(DataParam param) {
    	String responseText = FAIL;
    	try {
    		WmNoteManage wmNoteManage = this.lookupService(WmNoteManage.class);
    		wmNoteManage.updateRecord(param);
    		responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
		return new AjaxRenderer(responseText);
	}    
    
    @PageAction
   	public ViewRenderer deleteNote(DataParam param) {
    	WmNoteManage wmNoteManage = this.lookupService(WmNoteManage.class);
    	wmNoteManage.deletRecord(param);
       	return prepareDisplay(param);
   	}
    @PageAction
   	public ViewRenderer queryDayWork(DataParam param) {
    	String startTime = param.getString("startTime");
    	String endTime = param.getString("endTime");
    	String content = param.getString("content");
    	this.getSessionAttributes().put("startTime", startTime);
    	this.getSessionAttributes().put("endTime", endTime);
    	this.getSessionAttributes().put("content", content);
    	param.put("query", "true");
       	return prepareDisplay(param);
   	}
    
    @SuppressWarnings({ "unchecked", "rawtypes" })
	@PageAction
   	public ViewRenderer exportWordFile(DataParam param) {
    	User user = (User) this.getUser();
		param.put("USER_ID",user.getUserId());
		WmNoteManage wmNoteManage = this.lookupService(WmNoteManage.class);
    	List<DataRow> dayWorkRecords = getService().findRecords(param);
    	List<DataRow> noteRecords = wmNoteManage.findRecords(param);
    	
		String fileName =user.getUserName()+"日报";
		List<HashMap> logs = new ArrayList<HashMap>();
		
		for (int i=0;i < dayWorkRecords.size();i++){
			DataRow dataRow = dayWorkRecords.get(i);
			HashMap log = new HashMap();
			Date date =(Date) dataRow.get("TW_TIME");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String weekText = DateUtil.getWeekText(date);
			log.put("date",sdf.format(date)+weekText);
			
			List<HashMap> logContent = new ArrayList<HashMap>();
			String TW_CONTENT = dataRow.getString("TW_CONTENT");
			if("".equals(TW_CONTENT) || TW_CONTENT==null){
				HashMap contentMap = new HashMap();
				contentMap.put("text","");
				logContent.add(contentMap);
			}else{
				HashMap contentMap = new HashMap();
				contentMap.put("text",TW_CONTENT);
				logContent.add(contentMap);
			}
			
			log.put("contentList", logContent);
			log.put("rowIndex", 10*i+3);
			log.put("index", i+1);
			logs.add(log);
		}
		
		for(int k=0;k<noteRecords.size();k++){
			DataRow noteRow =noteRecords.get(k);
			HashMap noteLog = new HashMap();
			noteLog.put("date",""+noteRow.get("NOTE_TITLE"));
			String NOTE_DESCRIBE = noteRow.getString("NOTE_DESCRIBE");
			List<HashMap> logContent = new ArrayList<HashMap>();
			HashMap contentMap = new HashMap();
			contentMap.put("text",NOTE_DESCRIBE);
			logContent.add(contentMap);
			noteLog.put("contentList", logContent);
			logs.add(noteLog);
		}
		String fileType = "word";
		exportFile(logs, fileName, fileType);
       	return new NullRenderer();
   	}
    
	private void exportFile(Object model, String fileName, String fileType) {
		try {
			ExportFileHelper exportFileHelper = new ExportFileHelper(request, response);
			String templateDir = exportFileHelper.geTemplateDirPath();
			if ("word".equals(fileType)){
				String templateFile = "DayReportDoc.ftl";
				
				ByteArrayInputStream bais = exportFileHelper.buildHtml4Doc(templateDir,templateFile, model);
				exportFileHelper.exportWord(bais,fileName+".doc");				
			}else if("pdf".equals(fileType)){
				String templateFile = "DayReportPdf.ftl";
				
				String inputFileContent = exportFileHelper.buildHtml4Pdf(templateDir,templateFile, model);
				exportFileHelper.exportPdf(inputFileContent, fileName+".pdf");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
    
    @SuppressWarnings({ "unchecked", "rawtypes" })
   	@PageAction
    public ViewRenderer exportPdfFile(DataParam param) {
       	User user = (User) this.getUser();
   		param.put("USER_ID",user.getUserId());
   		WmNoteManage wmNoteManage = this.lookupService(WmNoteManage.class);
       	List<DataRow> dayWorkRecords = getService().findRecords(param);
       	List<DataRow> noteRecords = wmNoteManage.findRecords(param);
       	
   		String fileName =user.getUserName()+"日报";
   		List<HashMap> logs = new ArrayList<HashMap>();
   		
   		for (int i=0;i < dayWorkRecords.size();i++){
   			DataRow dataRow = dayWorkRecords.get(i);
   			HashMap log = new HashMap();
   			Date date =(Date) dataRow.get("TW_TIME");
   			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   			String weekText = DateUtil.getWeekText(date);
   			log.put("date",sdf.format(date)+weekText);
   			
   			List<HashMap> logContent = new ArrayList<HashMap>();
   			String TW_CONTENT = dataRow.getString("TW_CONTENT");
   			if("".equals(TW_CONTENT) || TW_CONTENT==null){
   				HashMap contentMap = new HashMap();
   				contentMap.put("text","");
   				logContent.add(contentMap);
   			}else{
   				HashMap contentMap = new HashMap();
				contentMap.put("text",TW_CONTENT);
				logContent.add(contentMap);
   			}
   			
   			log.put("contentList", logContent);
   			log.put("rowIndex", 10*i+3);
   			log.put("index", i+1);
   			logs.add(log);
   		}
   		
   		for(int k=0;k<noteRecords.size();k++){
   			DataRow noteRow =noteRecords.get(k);
   			HashMap noteLog = new HashMap();
   			noteLog.put("date",""+noteRow.get("NOTE_TITLE"));
   			String NOTE_DESCRIBE = noteRow.getString("NOTE_DESCRIBE");
   			List<HashMap> logContent = new ArrayList<HashMap>();
   			HashMap contentMap = new HashMap();
			contentMap.put("text",NOTE_DESCRIBE);
			logContent.add(contentMap);
   			noteLog.put("contentList", logContent);
   			logs.add(noteLog);
   		}
   		String fileType = "pdf";
		exportFile(logs, fileName, fileType);
        return new NullRenderer();
    }
    
    
    public ViewRenderer doQueryAction(DataParam param){
		return prepareDisplay(param);
	}
    
    public ViewRenderer doMoveUpAction(DataParam param){
		String nodeId = param.get(this.nodeIdField);
		WmNoteManage wmNoteManage = this.lookupService(WmNoteManage.class);
		wmNoteManage.changeCurrentSort(nodeId, true);
		param.put("rowIndex",param.getInt("NOTE_SORT")-1);
		return prepareDisplay(param);
	}
    public ViewRenderer doMoveDownAction(DataParam param){
		String nodeId = param.get(this.nodeIdField);
		WmNoteManage wmNoteManage = this.lookupService(WmNoteManage.class);
		wmNoteManage.changeCurrentSort(nodeId, false);
		param.put("rowIndex",param.getInt("NOTE_SORT")+1);
		return prepareDisplay(param);
	}
    protected WmDayworkManage getService() {
        return (WmDayworkManage) this.lookupService(this.getServiceId());
    }
   
}
